﻿using System;
using System.Windows.Forms;
using BLL;
using BLL.BomBLL;
using BLL.MaterialBLL;
using MDMUI.MaterialUI;
using Model;

namespace MDMUI
{
    public partial class Material : Form
    {
        private BLL.MaterialBLL.MaterialBLL _materialBLL = new BLL.MaterialBLL.MaterialBLL();
        private BomBLL _bomBLL = new BomBLL();
        private BOMItemBLL _bomItemBLL = new BOMItemBLL();

        public Material()
        {
            InitializeComponent();
            this.Load += new System.EventHandler(this.Material_Load);
        }

        private void Material_Load(object sender, EventArgs e)
        {
            // 加载物料类型到 ComboBox1
            LoadMaterialTypes();

            // 加载所有材料到 DataGridView
            LoadMaterials();
            LoadBoms();
        }

        private void LoadMaterialTypes()
        {
            List<string> materialTypes = _materialBLL.GetDistinctMaterialTypes();
            comboBox1.Items.Clear();
            comboBox1.Items.Add(""); // 添加空选项
            comboBox1.Items.AddRange(materialTypes.ToArray());
        }

        private void LoadDetailedTypes(string materialType)
        {
            // 清空前添加调试输出
            Console.WriteLine($"Loading detailed types for: {materialType}");

            comboBox2.Items.Clear();
            comboBox2.Items.Add("");

            try
            {
                List<string> detailedTypes = _materialBLL.GetDistinctDetailedTypes(materialType);

                // 验证是否获取到数据
                if (detailedTypes == null || detailedTypes.Count == 0)
                {
                    MessageBox.Show($"未找到 [{materialType}] 的详细类型");
                    return;
                }

                comboBox2.Items.AddRange(detailedTypes.ToArray());

                // 自动选择第一项（可选）
                if (comboBox2.Items.Count > 1) comboBox2.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载详细类型失败: {ex.Message}");
            }
        }

        private void LoadMaterials()
        {
            List<Model.Material> materials = _materialBLL.GetAllMaterials();
            MaterialData.DataSource = materials; // 确保这里绑定的是 List<Model.Material>
            SetDataGridViewColumnHeaders();
        }

        private void LoadBoms()
        {
            // 获取所有 BOM 数据
            List<Bom> boms = _bomBLL.GetAllBoms();

            // 将数据绑定到 DataGridView
            BOMData.DataSource = boms;
            SetDataGridViewColumnHeadersForBOM();

            // 默认选中第一行并加载对应的BOMItem
            if (boms.Count > 0)
            {
                BOMData.ClearSelection();
                BOMData.Rows[0].Selected = true;
                LoadBOMItemsBySelectedBom();
            }
        }
        private void SetDataGridViewColumnHeadersForBOM()
        {
            if (BOMData.Columns.Count == 0) return;

            // 设置列标题
            BOMData.Columns["BomId"].HeaderText = "BOM ID";
            BOMData.Columns["BomVersion"].HeaderText = "BOM版本";
            BOMData.Columns["SerialNumber"].HeaderText = "序列号";

            // 设置列宽
            BOMData.Columns["BomId"].Width = 100;
            BOMData.Columns["BomVersion"].Width = 200;
            BOMData.Columns["SerialNumber"].Width = 100;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem != null) // 增加空值检查
            {
                string selectedMaterialType = comboBox1.SelectedItem.ToString();
                if (!string.IsNullOrEmpty(selectedMaterialType))
                {
                    LoadDetailedTypes(selectedMaterialType);
                }
            }
        }

        private void material_select_Click(object sender, EventArgs e)
        {
            string materialType = comboBox1.SelectedItem?.ToString();
            string detailedType = comboBox2.SelectedItem?.ToString();
            int? materialId = null;
            if (!string.IsNullOrWhiteSpace(textBox1.Text) && int.TryParse(textBox1.Text, out int id))
            {
                materialId = id;
            }

            List<Model.Material> filteredMaterials = _materialBLL.SearchMaterials(materialType, detailedType, materialId);
            MaterialData.DataSource = filteredMaterials; // 确保这里绑定的是 List<Model.Material>
            SetDataGridViewColumnHeaders();
        }

        private void SetDataGridViewColumnHeaders()
        {
            MaterialData.Columns["MaterialId"].HeaderText = "物料ID";
            MaterialData.Columns["MaterialType"].HeaderText = "物料类型";
            MaterialData.Columns["DetailedMaterialType"].HeaderText = "详细类型";
            MaterialData.Columns["Quantity"].HeaderText = "数量";
            MaterialData.Columns["MaterialUnit"].HeaderText = "单位";
            MaterialData.Columns["MaterialDescription"].HeaderText = "描述";
            MaterialData.Columns["ConsumptionDeduction"].HeaderText = "消耗扣除";
            MaterialData.Columns["MaterialGroupNumber"].HeaderText = "物料组号";

            // 隐藏不需要的列
            MaterialData.Columns["ConsumptionDeduction"].Visible = false;
            MaterialData.Columns["MaterialGroupNumber"].Visible = false;
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            // 清空 ComboBox1 和 ComboBox2 的选中项
            comboBox1.SelectedIndex = -1; // 清空选中项
            comboBox2.SelectedIndex = -1; // 清空选中项

            // 重新加载物料类型到 ComboBox1
            LoadMaterialTypes();

            // 重新加载所有材料到 DataGridView
            LoadMaterials();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            // 检查是否有选中的行
            if (MaterialData.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 获取选中的行
            DataGridViewRow selectedRow = MaterialData.SelectedRows[0];
            int materialId = Convert.ToInt32(selectedRow.Cells["MaterialId"].Value);
            string materialName = selectedRow.Cells["MaterialDescription"].Value.ToString();

            // 确认删除对话框
            DialogResult result = MessageBox.Show($"确定要删除物料 '{materialName}' (ID: {materialId}) 吗？",
                                                  "确认删除",
                                                  MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    // 调用 BLL 删除方法
                    int rowsAffected = _materialBLL.DeleteMaterial(materialId);

                    if (rowsAffected > 0)
                    {
                        MessageBox.Show("物料删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 刷新数据
                        LoadMaterials();
                    }
                    else
                    {
                        MessageBox.Show("物料删除失败，请重试！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除物料时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            // 检查是否有选中的行
            if (MaterialData.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要修改的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 获取选中的行
            DataGridViewRow selectedRow = MaterialData.SelectedRows[0];
            int materialId = Convert.ToInt32(selectedRow.Cells["MaterialId"].Value);

            // 获取物料详细信息
            Model.Material selectedMaterial = _materialBLL.GetMaterialById(materialId);

            if (selectedMaterial == null)
            {
                MessageBox.Show("无法获取物料详细信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // 创建 UpMaterial 窗体实例
            UpMaterial upMaterialForm = new UpMaterial();

            // 将选中的物料信息填充到 UpMaterial 窗体的 TextBox 中
            upMaterialForm.txtMaterialType.Text = selectedMaterial.MaterialType;
            upMaterialForm.txtDetailedMaterialType.Text = selectedMaterial.DetailedMaterialType;
            upMaterialForm.txtQuantity.Text = selectedMaterial.Quantity?.ToString() ?? string.Empty;
            upMaterialForm.txtMaterialUnit.Text = selectedMaterial.MaterialUnit;
            upMaterialForm.txtMaterialDescription.Text = selectedMaterial.MaterialDescription;
            upMaterialForm.txtConsumptionDeduction.Text = selectedMaterial.ConsumptionDeduction;
            upMaterialForm.txtMaterialGroupNumber.Text = selectedMaterial.MaterialGroupNumber;

            // 将物料 ID 传递给 UpMaterial 窗体，用于后续的更新操作
            upMaterialForm.Tag = materialId;

            // 显示 UpMaterial 窗体
            upMaterialForm.ShowDialog();

            // 如果物料信息被修改，刷新物料数据
            if (upMaterialForm.DialogResult == DialogResult.OK)
            {
                LoadMaterials();
            }
        }
        private void LoadBOMItemsBySelectedBom()
        {
            if (BOMData.SelectedRows.Count > 0)
            {
                DataGridViewRow selectedRow = BOMData.SelectedRows[0];
                int bomId = Convert.ToInt32(selectedRow.Cells["BomId"].Value);
                LoadBOMItems(bomId);
            }
        }

        // 新增方法：加载指定BomId的BOMItems
        private void LoadBOMItems(int bomId)
        {
            List<BOMItem> bomItems = _bomItemBLL.GetBOMItemsByBomId(bomId);
            BOMITEM.DataSource = bomItems;
            SetDataGridViewColumnHeadersForBOMITEM();
        }

        // 新增方法：设置BOMITEM DataGridView的列标题
        private void SetDataGridViewColumnHeadersForBOMITEM()
        {
            if (BOMITEM.Columns.Count == 0) return;

            // 设置列标题
            BOMITEM.Columns["Sequence"].HeaderText = "序列";
            BOMITEM.Columns["MaterialType"].HeaderText = "物料类型";
            BOMITEM.Columns["DetailedMaterialType"].HeaderText = "详细物料类型";
            BOMITEM.Columns["MaterialNumber"].HeaderText = "物料号";
            BOMITEM.Columns["MaterialDescription"].HeaderText = "物料";

            // 隐藏不需要的列
            BOMITEM.Columns["BOMItemId"].Visible = false;
            BOMITEM.Columns["BomId"].Visible = false;
            BOMITEM.Columns["ProductId"].Visible = false;
        }
        private void BOMData_SelectionChanged(object sender, EventArgs e)
        {
            LoadBOMItemsBySelectedBom();
        }
    }
}